import request from '@/utils/request'

/**
 * 获取店铺分页列表
 * @param {Object} params - 查询参数
 * @param {number} params.pageNum - 页码
 * @param {number} params.pageSize - 每页数量
 * @param {string} params.name - 店铺名称搜索
 * @param {string} params.address - 地址搜索
 * @param {string} params.phone - 联系电话搜索
 * @param {number} params.rating - 推荐等级筛选
 * @param {string} params.status - 状态筛选
 * @returns {Promise} 店铺列表
 */
export const getFoodStorePage = async (params) => {
  try {
    console.log("发送店铺分页查询请求，参数:", params);
    
    // 构建查询参数对象，只包含有值的字段
    const queryParams = {}
    
    // 分页参数
    if (params.pageNum !== undefined) queryParams.pageNum = params.pageNum
    if (params.pageSize !== undefined) queryParams.pageSize = params.pageSize
    
    // 搜索参数 - 如果是搜索，只传一个字段进行模糊匹配
    if (params.name && params.name.trim()) {
      // 优先使用name字段进行搜索，后端应该支持模糊匹配店铺名称、地址、电话
      queryParams.name = params.name.trim()
    }
    
    // 筛选参数
    if (params.rating !== undefined && params.rating !== null) {
      queryParams.rating = params.rating
    }
    
    if (params.status !== undefined && params.status !== null) {
      queryParams.status = params.status
    }
    
    console.log("最终发送的查询参数:", queryParams);
    
    const response = await fetch('/api/admin/foodStore/page', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(queryParams)
    })

    console.log("响应状态:", response.status);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 检查响应是否有内容
    const text = await response.text()
    console.log("服务器原始响应:", text);
    
    if (!text) {
      throw new Error('服务器返回空响应')
    }

    let result
    try {
      result = JSON.parse(text)
    } catch (parseError) {
      console.error('JSON解析失败:', text)
      throw new Error('服务器返回的数据格式不正确')
    }
    
    if (result.code === 200) {
      return result.data
    } else {
      throw new Error(result.msg || '获取店铺列表失败')
    }
  } catch (error) {
    console.error('获取店铺列表失败:', error)
    throw error
  }
}

/**
 * 根据ID删除店铺
 * @param {number} id - 店铺ID
 * @returns {Promise} 删除结果
 */
export const deleteFoodStoreById = async (id) => {
  try {
    console.log("发送店铺删除请求，店铺ID:", id);
    
    const response = await fetch(`/api/admin/foodStore/delete/${id}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      }
    })

    console.log("响应状态:", response.status);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 检查响应是否有内容
    const text = await response.text()
    console.log("服务器原始响应:", text);
    
    if (!text) {
      throw new Error('服务器返回空响应')
    }

    let result
    try {
      result = JSON.parse(text)
    } catch (parseError) {
      console.error('JSON解析失败:', text)
      throw new Error('服务器返回的数据格式不正确')
    }
    
    if (result.code === 200) {
      return result
    } else {
      throw new Error(result.msg || '删除店铺失败')
    }
  } catch (error) {
    console.error('删除店铺失败:', error)
    throw error
  }
}

/**
 * 更新店铺状态
 * @param {number} id - 店铺ID
 * @param {string} status - 新状态
 * @returns {Promise} 更新结果
 */
export const updateFoodStoreStatus = async (id, status) => {
  try {
    const response = await request.put(`/shop/${id}/status`, { status })
    return response.data
  } catch (error) {
    throw error
  }
}

/**
 * 获取店铺详情
 * @param {number} id - 店铺ID
 * @returns {Promise} 店铺详情
 */
export const getFoodStoreById = async (id) => {
  try {
    const response = await request.get(`/shop/${id}`)
    return response.data
  } catch (error) {
    throw error
  }
}

/**
 * 创建店铺
 * @param {Object} data - 店铺数据
 * @param {File} coverImageFile - 封面图片文件
 * @returns {Promise} 创建结果
 */
export const createFoodStore = async (data, coverImageFile) => {
  try {
    console.log("发送店铺创建请求，数据:", data);
    console.log("封面图片文件:", coverImageFile);
    
    // 创建 FormData 对象
    const formData = new FormData()
    
    // 添加店铺基本信息
    if (data.name) formData.append('name', data.name)
    if (data.description) formData.append('description', data.description)
    if (data.category !== undefined) formData.append('category', data.category.toString())
    if (data.businessHours) formData.append('businessHours', data.businessHours)
    if (data.phone) formData.append('phone', data.phone)
    if (data.address) formData.append('address', data.address)
    if (data.rating !== undefined) formData.append('rating', data.rating.toString())
    if (data.longitude !== undefined) formData.append('longitude', data.longitude.toString())
    if (data.latitude !== undefined) formData.append('latitude', data.latitude.toString())
    if (data.priority !== undefined) formData.append('priority', data.priority.toString())
    if (data.status !== undefined) formData.append('status', data.status.toString())
    
    // 添加封面图片文件
    if (coverImageFile) {
      formData.append('coverImageFile', coverImageFile)
    }
    
    console.log("FormData 内容:");
    for (let [key, value] of formData.entries()) {
      console.log(key, value);
    }
    
    const response = await fetch('/api/admin/foodStore/insert', {
      method: 'POST',
      // 不设置 Content-Type，让浏览器自动设置 multipart/form-data
      body: formData
    })

    console.log("响应状态:", response.status);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 检查响应是否有内容
    const text = await response.text()
    console.log("服务器原始响应:", text);
    
    if (!text) {
      throw new Error('服务器返回空响应')
    }

    let result
    try {
      result = JSON.parse(text)
    } catch (parseError) {
      console.error('JSON解析失败:', text)
      throw new Error('服务器返回的数据格式不正确')
    }
    
    if (result.code === 200) {
      return result
    } else {
      throw new Error(result.msg || '创建店铺失败')
    }
  } catch (error) {
    console.error('创建店铺失败:', error)
    throw error
  }
}

/**
 * 更新店铺信息
 * @param {Object} data - 店铺数据（包含id）
 * @param {File} coverImageFile - 封面图片文件
 * @returns {Promise} 更新结果
 */
export const updateFoodStore = async (data, coverImageFile) => {
  try {
    console.log("发送店铺更新请求，数据:", data);
    console.log("封面图片文件:", coverImageFile);
    
    // 创建 FormData 对象
    const formData = new FormData()
    
    // 添加店铺基本信息
    if (data.id !== undefined) formData.append('id', data.id.toString())
    if (data.name) formData.append('name', data.name)
    if (data.description) formData.append('description', data.description)
    if (data.category !== undefined) formData.append('category', data.category.toString())
    if (data.businessHours) formData.append('businessHours', data.businessHours)
    if (data.phone) formData.append('phone', data.phone)
    if (data.address) formData.append('address', data.address)
    if (data.rating !== undefined) formData.append('rating', data.rating.toString())
    if (data.longitude !== undefined) formData.append('longitude', data.longitude.toString())
    if (data.latitude !== undefined) formData.append('latitude', data.latitude.toString())
    if (data.priority !== undefined) formData.append('priority', data.priority.toString())
    if (data.status !== undefined) formData.append('status', data.status.toString())
    
    // 添加封面图片文件
    if (coverImageFile) {
      formData.append('coverImageFile', coverImageFile)
    }
    
    console.log("FormData 内容:");
    for (let [key, value] of formData.entries()) {
      console.log(key, value);
    }
    
    const response = await fetch('/api/admin/foodStore/update', {
      method: 'POST',
      // 不设置 Content-Type，让浏览器自动设置 multipart/form-data
      body: formData
    })

    console.log("响应状态:", response.status);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 检查响应是否有内容
    const text = await response.text()
    console.log("服务器原始响应:", text);
    
    if (!text) {
      throw new Error('服务器返回空响应')
    }

    let result
    try {
      result = JSON.parse(text)
    } catch (parseError) {
      console.error('JSON解析失败:', text)
      throw new Error('服务器返回的数据格式不正确')
    }
    
    if (result.code === 200) {
      return result
    } else {
      throw new Error(result.msg || '更新店铺失败')
    }
  } catch (error) {
    console.error('更新店铺失败:', error)
    throw error
  }
}

/**
 * 批量删除店铺
 * @param {Array} ids - 店铺ID数组
 * @returns {Promise} 删除结果
 */
export const batchDeleteFoodStores = async (ids) => {
  try {
    const response = await request.delete('/shop/batch', { data: { ids } })
    return response.data
  } catch (error) {
    throw error
  }
}